package com.xu.cloud.common.log;

import org.springframework.boot.logging.LogFile;
import org.springframework.boot.logging.LoggingInitializationContext;
import org.springframework.boot.logging.log4j2.Log4J2LoggingSystem;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Objects;

/**
 * log4j2日志系统
 *
 * @author xuguan
 * @since 2024/11/1
 */
public class XuCloudLog4j2LoggingSystem extends Log4J2LoggingSystem {

    public XuCloudLog4j2LoggingSystem(ClassLoader classLoader) {
        super(classLoader);
    }

    @Override
    protected void loadDefaults(LoggingInitializationContext initializationContext, LogFile logFile) {
        String fileName = "log4j2.xml";
        if (Objects.nonNull(logFile)) {
            fileName = "log4j2-file.xml";
        } else {
            final Environment env = initializationContext.getEnvironment();
            final String profile = Arrays.stream(env.getActiveProfiles()).findFirst().orElse(null);
            if (StringUtils.hasText(profile)) {
                fileName = String.format("log4j2-%s.xml", profile);
            }
        }

        loadConfiguration(getPackagedConfigFile(fileName), logFile);
    }
}
